package com.github.livebase.util.http;

import com.github.livebase.util.base.CollectionsUtil;
import com.github.livebase.util.base.IOUtil;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CloseableResponse
 * @description:
 * @author: biao532
 * @create: 2024-04-03 14:11
 * @Version 1.0
 **/
public class CloseableResponse implements Closeable {
    private int code;
    private InputStream stream;
    private Map<String, List<String>> header;
    protected CloseableResponse() {
    }

    void setCode(int code) {
        this.code = code;
    }

    void setHeader(Map<String, List<String>> header) {
        this.header = header;
    }

    void setStream(InputStream stream) {
        this.stream = stream;
    }

    public int getCode() {
        return code;
    }

    public InputStream getStream() {
        return stream;
    }

    public String getHeader(String key) {
        return CollectionsUtil.getOrDefault(getHeaders(key), 0, null);
    }

    public List<String> getHeaders(String key) {
        if (header == null) {
            return null;
        }
        return header.get(key);
    }

    @Override
    public void close() throws IOException {
        header = null;
        stream.close();
    }

    @Override
    public String toString() {
        try {
            return "CloseableResponse{" +
                    "code=" + code +
                    ", stream=" + IOUtil.toString(stream) +
                    ", header=" + header +
                    '}';
        } catch (IOException e) {
            return "CloseableResponse{" +
                    "code=" + code +
                    ", stream=" + e.getMessage() +
                    ", header=" + header +
                    '}';
        }
    }
}
